import React, { useState, useEffect, useContext, useRef } from 'react'
import { LayoutContext } from '&/pages/layouts/context'
import Container from '@/appComponents/Container'
import { DownloadOutlined } from '@ant-design/icons'
import downloadExcelImg from '&/commonjs/downloadExcelImg'
import { setEmergencyClueList } from '../../api/electricity'
import Filter from './Filter'
import ShareValue from './ShareValueNew'
import { getEmergencyList } from '&/api/electricity'
import {
  Table,
  Button,
  message,
  Modal,
  Collapse,
  Tag,
  Spin,
  Pagination,
  Image
} from 'antd'
import './style.scss'
import dayjs from 'dayjs'
import ModerOther from '../EnterpriseEmergency/ModerOther'
import ShareValueNew from '../EnterpriseEmergency/ShareValueNew'
import ModalEcharts from '../ProcessAssessment/ModalEcharts'
import axios from 'axios'

const { Panel } = Collapse
const EnterpriseEmergency = () => {
  const { activePlan } = useContext(LayoutContext)
  const values = JSON.parse(localStorage.getItem('user')) || {}
  const [downLoading, setDownLoading] = useState(false)
  const [hareValue, setHareValue] = useState()
  const [listArr, setListArr] = useState([])
  const [newRecordData, setNewRecordData] = useState([])
  const [list, setList] = useState([])
  const [line_warn, set_line_warn] = useState(null)
  const [tableData, setTableData] = useState([])
  const [key, setkey] = useState() //选中折叠面板的key
  const [loading, setLoading] = useState(true)
  const [pageInfo, setPageInfo] = useState()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [visible, setVisible] = useState(false) //弹窗的打开与关闭.
  const [records, setRecords] = useState()
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [instance, setInstance] = useState(null)
  const [recordSing, setRecordSing] = useState() //点击详情所拿到的数据
  const ref = useRef(null)
  const [paramsData, setParamsData] = useState({
    role_level: values?.role_level,
    adm_id: values?.adm_id,
    county_id: -1, //区
    industry_type_id: -1, //行业
    warn_type: -1,
    ent_name: '',
    page: 1,
    page_size: 20
    // plan_id: 57
  })
  const columns = [
    {
      title: '序号',
      width: 50,
      render: (_, __, index) => `${index + 1}`,
      align: 'center'
    },
    {
      title: '开始-结束时间',
      dataIndex: 'time_area',
      key: 'time_area',
      align: 'center',
      width: 200
    },
    {
      width: 100,
      title: '累计时长',
      dataIndex: 'time_duration',
      key: 'time_duration',
      align: 'center'
    },
    {
      width: 100,
      title: '问题描述',
      dataIndex: 'result_content',
      key: 'result_content',
      align: 'center'
    },
    {
      width: 100,
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center'
    },
    // {
    //   width: 100,
    //   title: '备注图片',
    //   dataIndex: 'activeimg',
    //   key: 'activeimg',
    //   align: 'center',
    //   render: (v) => {
    //     return <Image src={v} />
    //   }
    // },
    {
      title: '操作',
      width: 140,
      align: 'center',
      render: (_, record) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'space-evenly' }}>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                DetailsData(record)
              }}
            >
              详情
            </Button>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                confirm_xiansuo(record)
              }}
            >
              生成问题
            </Button>
          </div>
        )
      }
    }
  ]
  const column = [
    {
      title: '序号',
      width: 50,
      render: (_, __, index) => `${index + 1}`,
      align: 'center'
    },
    {
      title: '预案名称',
      dataIndex: 'plan_name',
      key: 'plan_name',
      align: 'center'
    },
    {
      title: '企业名称',
      dataIndex: 'ent_name',
      key: 'ent_name',
      align: 'center'
    },
    {
      title: '所属区',
      dataIndex: 'county_name',
      key: 'county_name',
      align: 'center'
    },
    {
      title: '所属街乡',
      dataIndex: 'town_name',
      key: 'town_name',
      align: 'center'
    },
    {
      title: '所属行业',
      dataIndex: 'industry_type_name',
      key: 'industry_type_name',
      align: 'center'
    },
    {
      title: '措施要求',
      dataIndex: 'measure',
      key: 'measure',
      align: 'center'
    },
    {
      title: '报警次数',
      dataIndex: 'taotal_counts',
      key: 'taotal_counts',
      align: 'center'
    },
    {
      title: '报警总时长',
      dataIndex: 'total_warning_time',
      key: 'total_warning_time',
      align: 'center'
    }
  ]
  const getParams = (paramsData) => {
    let newParamsData = {}
    for (let key in paramsData) {
      if (paramsData[key] != (-1 || '-1')) {
        newParamsData[key] = paramsData[key]
      }
    }
    return newParamsData
  }
  const DownData = (value) => {
    setIsModalOpen(true)
    const warnArr = [
      {
        warn_code: value.warn_code,
        ent_name: value.ent_name
      }
    ]
    setNewRecordData(warnArr)
  }
  const DetailsData = (value) => {
    setRecords(value)

    const dev_Arr = [value.warn_id, value.result_content]
    setIsModalOpen(true)
  }
  //是否确定生成线索
  const confirm_xiansuo = (e) => {
    //重组成线索信息
    let time_list = line_warn['children'].map((item) => ({
      start_time: item.start_time,
      end_time: item.end_time
    }))
    let line_warn_data = { ...line_warn, ...e, time_list }
    //  ///...这里是接着些后续的逻辑
    Modal.confirm({
      title: '确认',
      content: '是否确认生成报警问题?',
      onOk() {
        let clue_data = {
          plan_name:line_warn_data.plan_name,
          ent_name:line_warn_data.ent_name,
          county_name:line_warn_data.county_name,
          town_name:line_warn_data.town_name,
          measure:line_warn_data.measure,
          content:line_warn_data.result_content,
          start_time:line_warn_data.start_time,
          end_time : line_warn_data.end_time,
          total_duration:line_warn_data.time_duration,
          active_img:line_warn_data.activeimg,
          warn_counts:line_warn_data.taotal_counts,
          industry_type:line_warn_data.industry_type_name,
          ent_id:line_warn_data.ent_id
        }
        setEmergencyClueList(clue_data).then((res) => {
          Modal.info({
            title:res
          })
        })
      },
      onCancel() {

      }
    })
  }
  const formatExeclData = (data) => {
    // const cloneData = data.map((item) => {
    //   const [{ warn_count, warn_type_name }] = item.content || []
    //   return {
    //     ...item,
    //     feedback_status: item.feedback_status == 0 ? '未反馈' : '已反馈',
    //     assign_status: item.assign_status == 0 ? '未下发' : '已下发',
    //     warn_count,
    //     warn_type_name,
    //     total_duration: item.warn_duration
    //   }
    // })

    var items = []
    if (listArr.length) {
      items = data.filter((d) => listArr.includes(d.warn_id))
    } else {
      items = data
    }

    return items
  }
  const handleShare = (values) => {
    setHareValue(values)
  }
  const handleOk = () => {
    if (hareValue) {
      if (!hareValue[0]?.description) {
        message.warning('描述信息未填写,请输入!')
        return
      }

      setIsModalOpen(false)
      onReload()
    }
  }
  const download = async () => {
    setDownLoading(true)
    // const { data } = await loadDataAll()
    // const execlData = formatExeclData(data)
    downloadExcelImg(list, column, '报警列表')
    setDownLoading(false)
  }
  const onQuery = async () => {
    setLoading(true)
    let json = getParams(paramsData)
    if (json.ent_name) {
      json.page = 1
    }
    let result = await getEmergencyList({
      ...json,
      plan_id: activePlan.plan_id
    })
    setLoading(false)
    if (result.data.length) {
      setPageInfo(result.page_info)
      setList(result.data)
    } else {
      setList([])
    }
  }
  const handleClick = (data) => {
    setkey(data)
    let result = list[data[0]]
    if (result) {
      setTableData(result.children)
    }
    set_line_warn(result)
  }
  const handText = (data) => {
    return (
      <div className="Collapse_text">
        <div>{data.plan_name}</div>
        <div>{data.ent_name}</div>
        <div>{data.county_name}</div>
        <div>{data.town_name}</div>
        <div>{data.industry_type_name}</div>
        <div
          style={{
            width: data.measure.length > 40 ? 350 : '',
            textOverflow: 'ellipsis',
            overflow: 'hidden'
          }}
        >
          {data.measure}
        </div>
        <div>{data.taotal_counts}</div>
        <div>{data.total_warning_time}</div>
      </div>
    )
  }
  const onChangePage = (page, page_size) => {
    setParamsData((state) => {
      state.page = page
      state.page_size = page_size
      return { ...state }
    })
    onQuery()
  }
  useEffect(() => {
    setParamsData((state) => {
      state.start_time = dayjs(activePlan.start_time).format(
        'YYYY-MM-DD HH:00:00'
      )
      state.end_time = dayjs(activePlan.end_time).format('YYYY-MM-DD HH:00:00')
      onQuery()
      return {
        ...state
      }
    })
  }, [activePlan.plan_id])
  return (
    <Container>
      <Container.ContainerQuery title="查询条件">
        <Filter
          onQuery={onQuery}
          paramsData={paramsData}
          setParamsData={setParamsData}
          loading={loading}
        />
      </Container.ContainerQuery>
      <Container.ContainerContent
        title={
          <div>
            <span>查询结果</span>
            <span style={{ color: '#305bff', 'font-size': '20px' }}>
              &nbsp;
              <span style={{ color: 'gray', 'font-size': '16px' }}>合计</span>
              {pageInfo && pageInfo.total_number !== undefined
                ? pageInfo.total_number
                : '加载中'}
              <span style={{ color: 'gray', 'font-size': '16px' }}>
                {' '}
                家企业触发报警
              </span>
            </span>
          </div>
        }
        extra={
          <div>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              loading={downLoading}
              disabled={!list.length}
              onClick={async () => {
                setDownLoading(true)
                await download()
                setDownLoading(false)
              }}
            >
              导出
            </Button>
          </div>
        }
      >
        <div className="Collapse_columns">
          <div>预案名称</div>
          <div>企业名称</div>
          <div>所属区</div>
          <div>所属街乡</div>
          <div>所属行业</div>
          <div>措施要求</div>
          <div>报警次数</div>
          <div>报警总时长</div>
        </div>
        <div className="Collapse_box">
          <Spin spinning={loading}>
            <Collapse
              activeKey={key}
              // collapsible='header'
              expandIconPosition={'end'}
              onChange={handleClick}
              accordion
            >
              {list.length > 0 &&
                list.map((item, index) => {
                  return (
                    <Panel header={handText(item)} key={index}>
                      <Table
                        bordered
                        tableLayout="fixed"
                        loading={loading}
                        columns={columns}
                        dataSource={tableData}
                        // rowSelection={{
                        //   ...rowSelection,
                        //   checkStrictly
                        // }}
                        size="middle"
                        rowKey={(row) => {
                          return JSON.stringify(row)
                        }}
                        pagination={true}
                        scroll={{
                          // x: 'calc(700px + 50%)',
                          y: '60vh'
                        }}
                      />
                    </Panel>
                  )
                })}
            </Collapse>
          </Spin>
        </div>
        {list.length > 0 ? (
          <Pagination
            className="Collapse_page"
            current={pageInfo.page}
            total={pageInfo.total_number}
            pageSize={pageInfo.page_size}
            showTotal={(total) => `共${total}条数据`}
            onChange={(page, pageSize) => {
              onChangePage(page, pageSize)
            }}
          />
        ) : (
          '暂无数据'
        )}
        <ModalEcharts
          record={records}
          open={isModalOpen}
          setOpen={setIsModalOpen}
        />
        {/*<Modal*/}
        {/*  title="生成线索"*/}
        {/*  destroyOnClose={true}*/}
        {/*  open={false}*/}
        {/*  confirmLoading={confirmLoading}*/}
        {/*  centered={true}*/}
        {/*  width={600}*/}
        {/*  onOk={handleOk}*/}
        {/*  onCancel={() => setIsModalOpen(false)}*/}
        {/*>*/}
        {/*  /!* <ShareValue*/}
        {/*  handleShare={handleShare}*/}
        {/*// newRecordData={newRecordData}*/}
        {/*></ShareValue> *!/*/}
        {/*  <ShareValueNew*/}
        {/*    handleShare={handleShare}*/}
        {/*    newRecordData={newRecordData}*/}
        {/*    recordSing={recordSing}*/}
        {/*    setInstance={setInstance}*/}
        {/*    // newRecordData={newRecordData}*/}
        {/*  ></ShareValueNew>*/}
        {/*</Modal>*/}
      </Container.ContainerContent>
    </Container>
  )
}
export default EnterpriseEmergency
